package cn.liumouren.tool.security.autoconfigure.component.interceptor;

import cn.liumouren.tool.security.core.DlInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口测速
 *
 * @author Daniel Liu
 * @date 2021/3/12 16:19
 */
@Slf4j
public class ApiMeasureInterceptor extends DlInterceptor {

    private final ThreadLocal<Long> enterTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("api测速Interceptor...");
        enterTime.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String blank = "                                      ";
        if (handler instanceof HandlerMethod) {
            String servletPath = request.getServletPath();
            if (servletPath.length() < blank.length()) {
                blank = blank.substring(servletPath.length());
            } else {
                blank = "";
            }
            log.info("{}{} --> {}ms", servletPath, blank, System.currentTimeMillis() - enterTime.get());
        }
    }
}
